package com.xbsg.protocol.xf.server.netty;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import org.springframework.stereotype.Component;


@Component
public class MyNettyServer {
//    @Autowired
//    private MyServerHandler serverHandler;

    public void start(int port) throws Exception {
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG, 128)
                    .childOption(ChannelOption.SO_KEEPALIVE, true)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
//                            socketChannel.pipeline().addLast(
//                                    new MyMessageDecoder(),
//                                    serverHandler);
//                            ch.pipeline().addLast(new StringDecoder());
//                            ch.pipeline().addLast(new StringEncoder());
                            ByteBuf delemiter= Unpooled.buffer();
                            delemiter.writeBytes("#".getBytes());
                            delemiter.writeBytes("#".getBytes());
                            //先使用DelimiterBasedFrameDecoder解码，以&作为分割符
                            ch.pipeline().addLast(new DelimiterBasedFrameDecoder(1024, true, true,delemiter));
                            // 添加自定义的业务处理器
                            ch.pipeline().addLast(new MyServerHandler());
                        }
                    });
            System.out.println("消防监控服务已经启动..." + "端口号: " + port);
            //绑定端口号，启动服务端
            ChannelFuture channelFuture = bootstrap.bind(port).sync();
            //对关闭通道进行监听
            channelFuture.channel().closeFuture().sync();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}

